package com.weitu.workflow.demo.controller;

import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.workflow.definition.constant.FlowDefConstants;
import com.weitu.workflow.demo.entity.LeaveApplication;
import com.weitu.workflow.demo.service.LeaveApplicationService;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowBusiness.entity.FlowBusiness;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.IProcessInstance;
import org.fireflow.engine.impl.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/workflow/demo")
public class LeaveApplicationController extends BaseController {

    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "workflow/demo";
    @Autowired
    private LeaveApplicationService leaveApplicationService;//流程管理Service
    @Autowired
    private FlowManagementService flowManagementService;//流程管理service
    private WorkflowReview workflowReview;

    public WorkflowReview getWorkflowReview() {
        return workflowReview;
    }

    public void setWorkflowReview(WorkflowReview workflowReview) {
        this.workflowReview = workflowReview;
    }

    /***
     * 跳转到请假单列表页面
     * @return
     */
    @RequestMapping(value = "/list")
    public String listView() {
        return MODULE_BATH_PATH + "/list";
    }

    /***
     * 查询请假单列表数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/findLeaveApplicationList")
    public Object findLeaveApplicationList(HttpServletRequest request) {

        Map<String, Object> map = new HashMap<String, Object>();

        //获取前台参数
        this.putParametersIntoMap(map);
        if(map.get("sort")==null){
            request.setAttribute("sort","createTime");
            request.setAttribute("order","desc");
        }

        Integer totalNum = this.leaveApplicationService.queryLeaveApplicationCount(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);

        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView",pageView);
        List<LeaveApplication> leaveApplicationList =this.leaveApplicationService.queryLeaveApplicationList(map);

        return pagination.flushDataGridData(leaveApplicationList);
    }
    /***
     * 跳转到请假单添加页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    public ModelAndView addView(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(MODULE_BATH_PATH + "/add");
        return modelAndView;
    }

    /**
     * 保存请假单
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addLeaveApplication",method = RequestMethod.POST)
    @SystemLog(module = "请假管理",methods = "新建请假单")
    public AjaxResult addLeaveApplication(HttpServletRequest request){
        User crrentUser=this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);
        paramMap.put("id", IDGenerator.getId());
        paramMap.put("createTime", DateTimeUtil.formatterDateTime());
        paramMap.put("createUserId", crrentUser.getId());
        int i=this.leaveApplicationService.addLeaveApplication(paramMap);

        if (i==1){
            result.setMessage("保存成功！");
            result.setSuccess(true);
            return result;
        }else {
            result.setMessage("保存失败！");
            result.setSuccess(false);
            return result;
        }
    }
    /**
     * 提交请假单
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitLeaveApplication",method = RequestMethod.POST)
    @SystemLog(module = "请假管理",methods = "提交请假单")
    public AjaxResult submitLeaveApplication(HttpServletRequest request)throws Exception{
        User crrentUser=this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);
        //获取请假单信息//获取请假单信息
        String leaveApplicationId=paramMap.get("id").toString();//请假单id
        LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        //设置流程变量
        Map<String,String> dataMap=new HashMap<String, String>();
        String nextUserId=paramMap.get("nextUserId").toString();//第一环节处理人
        dataMap.put(FlowDefConstants.FLOW_FIRSTUSER_ID,nextUserId);
        //启动流程实例
        IProcessInstance processInstance=this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_LEAVEAPPLICATION,leaveApplicationId,leaveApplication.getContent(),crrentUser.getName(),dataMap);

        //int i=1/0;
        if (processInstance!=null){

            result.setMessage("提交成功！");
            result.setSuccess(true);
        }else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }
    /***
     * 跳转到请假单审批页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/leaveApplicationVerify")
    public ModelAndView leaveApplicationVerify(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        String leaveApplicationId=paramMap.get("businessId").toString();//获取业务id，以businessId命名
        //工作项id
        String workItemId=paramMap.get("workItemId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType=paramMap.get("formType")!=null?Integer.parseInt(paramMap.get("formType").toString()):0;
        modelAndView.addObject("workItemId",workItemId);
        modelAndView.addObject("formType",formType);

        //获取意见信息
        WorkflowReview workflowReview=this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview",workflowReview);

        //获取请假单信息
        LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        modelAndView.addObject("leaveApplication",leaveApplication);
        modelAndView.setViewName(MODULE_BATH_PATH + "/verify");
        return modelAndView;
    }

    /**
     * 审批请假单
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "verifyLeaveApplication",method = RequestMethod.POST)
    public AjaxResult verifyLeaveApplication(HttpServletRequest request)throws Exception{
        String workItemId=request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview=this.flowManagementService.getWorkflowReviewByRequest(request,"workflowReview",workItemId);
        //保存处理结果
        boolean boo=this.flowManagementService.saveWorkflowReview(workflowReview);

        //结束环节，继续流程向下执行
        if (boo){
            this.flowManagementService.workItemComplete(workItemId);
        }
        System.out.println(workflowReview.getComments());
       /* User crrentUser=this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        String leaveApplicationId=paramMap.get("id").toString();//请假单id
        //启动流程实例
        IProcessInstance processInstance=this.flowManagementService.flowCreateAndRun("WorkFlow20170322151013",leaveApplicationId,crrentUser.getName());
        //int i=1/0;
        if (processInstance!=null){
            result.setMessage("提交成功！");
            result.setSuccess(true);
        }else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }*/
        AjaxResult result = new AjaxResult();
        if (boo){
            result.setMessage("提交成功！");
            result.setSuccess(true);
        }else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }

}
